import { Fragment, defineComponent, reactive, watch } from 'vue';
import { searchPage, wrap, tabs, history, routeInput, searchInput, poiList, clearfix, content, action, title, name, desc, floorName, thumbnail, item, boxLishi, icon, keyword, tabList, tabListActive, back, floorInfo } from './Search.module.scss';
import { map, marker, navi, poi } from '@/store';
import { PoiInfo, poiTypeInterface, FloorInfo } from '@/utils/type';
import { ElCol, ElInput, ElRow } from 'element-plus';
import navImg from '@/assets/img/search/icon-nav.png';
import searchImg from '@/assets/img/menu/icon-search.png';
import smallImg from '@/assets/img/search/icon-search-small.png';
import thumbImg from '@/assets/img/search/thumb.png';
import mapImg from '@/assets/img/search/map.png';
import mapImg2 from '@/assets/img/search/map2.png';
import listImg from '@/assets/img/search/list.png';
import listImg2 from '@/assets/img/search/list2.png';
import { fmapObj } from '../fmap/Fmap';
import { closeToast, showLoadingToast } from 'vant';

/*
---搜索页面文件
---重构：
*/
export const searchObj = reactive({
    historyList: [] as PoiInfo[],
    resultList: [] as PoiInfo[],
    isShowRes:false,
})
export default defineComponent({
    name: 'Search',
    data() {
        return {
            keyword: '',
            keywordTips: '历史',
            isShow: false,
        }
    },
    methods: {
        search(name: string) {
            if (!name) return;
            this.keywordTips = name ? name : '历史';
            //把查询的历史记录，存入缓存
            poi.requestPoiList3(this.keywordTips);
            //显示标记（终点）
            this.markEnd();
        },
        markEnd() {
            marker.removeImageMarker();
            searchObj.resultList.forEach((item) => {
                //显示标记（终点）
                marker.setImageMarker(
                    {
                        x: item.coordinateX,
                        y: item.coordinateY,
                        floorId: item.floorId,
                    },
                    true
                );
            });
        },
        backToMenu() {
            this.keyword = "";
            poi.infoType = "details";
            map.menuFlag = true;
            map.searchFlag = false;
            searchObj.isShowRes = false;
            marker.removeImageMarker();
        },
        chooseTab(type) {
            if (type == 1) {
                this.isShow = true;
            } else {
                this.isShow = false;
                fmapObj.top = "200px"
                poi.infoType = "details";
                //显示标记（终点）
                this.markEnd();
            }
        },
        goPath(data) {
            map.curPageType = "path";
            let val = {
                fid: data.fid,
                coordinateX: data.coordinateX,
                coordinateY: data.coordinateY,
                poiName: data.poiName,
                poiIntro: data.poiIntro,
                floorId: data.floorId,
            };
            let temp = localStorage.getItem("historyPoiList");
            if (temp) {
                searchObj.historyList = JSON.parse(temp);
                if (temp.indexOf(JSON.stringify(val)) == -1) {
                    searchObj.historyList.unshift(val);
                    localStorage.setItem(
                        "historyPoiList",
                        JSON.stringify(searchObj.historyList)
                    );
                } else {
                    //有搜索记录，删除之前的旧记录，将新搜索值重新push到数组首位
                    let i = searchObj.historyList.findIndex(function (item) {
                        return item.poiName == val.poiName;
                    });

                    searchObj.historyList.splice(i, 1);
                    searchObj.historyList.unshift(val);
                    localStorage.setItem(
                        "historyPoiList",
                        JSON.stringify(searchObj.historyList)
                    );
                }
            } else {
                searchObj.historyList.unshift(val);
                localStorage.setItem("historyPoiList", JSON.stringify(searchObj.historyList));
            }

            poi.start = poi.now;
            poi.end = data;
            // 导航准备，检验起点终点是否合格
            if (navi.verifyRoutePois()) {
                showLoadingToast({
                    message: '路线规划中',
                    forbidClick: true,
                    duration: 0,
                });
                //规划路线并显示
                navi.startRoute();
                closeToast();
            }
        },
    },
    render() {
        return <Fragment>
            <div class={searchPage} v-show={map.searchFlag}>
                <div class={wrap}>
                    <ElRow gutter={20}>
                        <ElCol class={routeInput} span={20}>
                            <ElInput
                                class={searchInput}
                                onChange={this.search}
                                v-model={this.keyword}
                                autofocus={true}
                                placeholder="请输入位置"
                                v-slots={{
                                    prefix: () => <img style={{ width: '14px' }} src={searchImg} alt="" />,
                                }}
                            />
                        </ElCol>
                        <ElCol span={4} >
                            <div class={`${back} flex-center`} onClick={this.backToMenu}>取消</div>
                        </ElCol>
                        <div class={tabs}>
                            <div class={`${tabList} ${this.isShow ? tabListActive : ''}`} onClick={() => this.chooseTab(1)}>
                                {this.isShow ? <img src={listImg} alt="" /> : <img src={listImg2} alt="" />}
                                <text>列表模式</text>
                            </div>
                            <div class={`${tabList} ${this.isShow ? '' : tabListActive}`} onClick={() => this.chooseTab(2)}>
                                {this.isShow ? <img src={mapImg2} alt="" /> : <img src={mapImg} alt="" />}
                                <text>地图模式</text>
                            </div>
                        </div>
                        {this.isShow && <ElCol
                            span={24}
                            style="height: calc(100vh - 80px); overflow: auto"
                        >
                            <p class={title}>
                                以下为<span class={keyword}>{this.keywordTips}</span>搜索记录
                            </p>
                            {(map.searchFlag && !searchObj.isShowRes) ? <div class={history}>
                                {searchObj.historyList?.map((h: any, index: number) => {
                                    if (h.fid !== 0) {
                                        return <div class={`${item} ${clearfix}`}>
                                            <div class={boxLishi}>
                                                <div class={icon}>
                                                    <img src={smallImg} alt="" />
                                                </div>
                                                <div class={content}>
                                                    <div class={title}>{h.poiName}</div>
                                                    <div class={desc}>{h.poiIntro}</div>
                                                </div>
                                                <div class={`${action} flex-center`} onClick={() => this.goPath(searchObj.historyList[index])}>
                                                    <img src={navImg} />
                                                </div>
                                            </div>
                                        </div>
                                    } else {
                                        return <div class={`${item} ${clearfix}`}>
                                            <div class={boxLishi} onClick={() => this.search(h.poiName)}>
                                                <div class={icon}>
                                                    <img src={smallImg} alt="" />
                                                </div>
                                                <div class={content}>
                                                    <div class={title}>{h.poiName}</div>
                                                </div>
                                            </div>
                                        </div>
                                    }
                                })}
                            </div> : <div class={poiList}>
                                {searchObj.resultList?.map((r: any, index: number) => {
                                    return <ElCol span={24}>
                                        <div class={`${item} ${clearfix}`} onClick={() => this.goPath(searchObj.resultList[index])}>
                                            <div class={thumbnail}>
                                                <img src={r.poiImgMoblie} alt="" />
                                                {/* {r.floorId > 0 ? <div class={floorName}>
                                                    {r.floorId}F
                                                </div> : <div class={floorName}>B1</div>} */}
                                            </div>
                                            <div class={content}>
                                                <div class={name}>
                                                    {r.poiName}
                                                </div>
                                                <div class={floorInfo}>
                                                    {r.floorId > 1 ? <div>
                                                        {r.floorId}F
                                                    </div> : <div>B1</div>}
                                                    <div class={desc}>{r.distance}米</div>
                                                </div>
                                            </div>
                                            <div class={`${action} flex-center`}>
                                                <img src={navImg} />
                                            </div>
                                        </div>
                                    </ElCol>
                                })}
                            </div>}
                        </ElCol >}
                    </ElRow >
                </div >
            </div >
        </Fragment >;
    },
});